package com.hzit.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import com.alibaba.fastjson2.JSON;

import com.hzit.cart.api.domain.Item;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Component
@RabbitListener(queues = "updateStatus")
public class SkuListener {
	@Autowired
	private ElasticsearchClient client;
	/**
	 * 1. 接受到hzit-manager发来的审核通过的sku列表商品后，同步到索引库中
	 * @param msg
	 */
	@RabbitHandler
	public void getMessage(String msg) throws IOException {
		//1.1 将字符串转换为List<Item>
		List<Item> items = JSON.parseArray(msg, Item.class);
		//1.2 添加到索引库中
		BulkRequest.Builder builder = new BulkRequest.Builder();
		for (Item item : items) {
			//① 得到规格字符串
			String spec = item.getSpec();
			//② 转换为map
			Map map = JSON.parseObject(spec, Map.class);
			//③ 将转换后的map与item中的specMap字段绑定
			item.setSpecMap(map);
			//④ 向构造器中添加一个操作operation
			builder.operations(op->op.index(
					idx->idx.index("item")
							.id(item.getId() + "")
							.document(item)
			));
		}
		//2.3 利用索引构建器构造索引并生成索引库
		client.bulk(builder.build());
		System.out.println("添加到索引库成功！");
	}


}
